package demo;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.*;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import top.lingkang.mmt.entity.UserEntity;
import top.lingkang.mmt.mapper.UserMapper;

import java.io.InputStream;
import java.util.List;

/**
 * @author lingkang
 * Created by 2024/2/28
 */
public class Demo01 {
    public static void main(String[] args) throws Exception {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://localhost:3306/test?useSSL=true&serverTimezone=UTC");
        config.setUsername("root");
        config.setPassword("123456");
        config.setMaximumPoolSize(3);
        HikariDataSource dataSource = new HikariDataSource(config);

        Configuration configuration = new Configuration();
        // 用for循环加载所有 xml

        InputStream inputStream = Resources.getResourceAsStream("mapper/IdEntityAssignMapper.xml");
        XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, "mapper/IdEntityAssignMapper.xml",
                configuration.getSqlFragments());
        mapperParser.parse();

         inputStream = Resources.getResourceAsStream("mapper/OtherMapper.xml");
         mapperParser = new XMLMapperBuilder(inputStream, configuration, "mapper/OtherMapper.xml",
                configuration.getSqlFragments());
        mapperParser.parse();


        // 配置
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("dev", transactionFactory, dataSource);
        configuration.setEnvironment(environment);
        configuration.setMapUnderscoreToCamelCase(true);// 下划线转化驼峰

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

        // 查询
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        System.out.println(mapper.selectAll());// 查询所有

        mapper = session.getMapper(UserMapper.class);
        System.out.println(mapper.selectAll());// 查询所有

        List<UserEntity> list = session.selectList("other.selectAll");
        System.out.println(list);

        session.close();
    }

}
